<template>
  <div id="main">
    <h2>待办事件管理</h2>
    <div class="head">
      <el-button type="primary" style="margin: 20px" @click="handleOpen('添加突发事案件', 1)">添加待办事件</el-button>
      <el-input v-model="searchTableInfo" placeholder="请输入搜索内容" style="width:240px;float: right;margin:20px;" />
    </div>
    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          label="序号"
          type="index"
          align="center"
        >
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <!-- <el-table-column
          label="事件id"
          type="index"
          align="center"
          prop="emergencyId"
        />  -->
        <el-table-column
          align="center"
          prop="emergencyTitle"
          label="事件标题"
        />

        <el-table-column
          align="center"
          prop="emergencyTime"
          label="发生时间"
        />

        <el-table-column
          align="center"
          prop="emergencyType"
          label="事件类型"
        />

        <el-table-column
          align="center"
          prop="emergencyInfo"
          label="事件描述"
        />

        <el-table-column
          align="center"
          prop="emergencyInfo"
          label="责任人"
        />

        <!-- <el-table-column
          align="center"
          prop="emergencyLoc"
          label="发生地点"
        /> -->
        <el-table-column
          align="center"
          prop="emergencyStatus"
          label="完成状态"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.emergencyStatus=='处理中'"> <p style="color: red;font-weight: 800;">处理中</p> </span>
            <span v-if="scope.row.emergencyStatus=='已解决'"><p style="color:  rgb(14, 189, 14);font-weight: 800;">已解决</p> </span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="250px">
          <template slot-scope="Scope">
            <el-button type="primary" icon="el-icon-edit" @click="handleOpen('修改事件', 2, Scope.row.emergencyId)">查看/编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="handleDelete(Scope.row.emergencyId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog title="" :close-on-click-modal="false" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form ref="emergency" :model="emergency" label-position="top" :rules="rules">

        <el-form-item prop="emergencyTitle" label="事件标题" :label-width="formLabelWidth">
          <el-input v-model="emergency.emergencyTitle" autocomplete="off" />
        </el-form-item>

        <el-form-item prop="emergencyInfo" label="事件描述" :label-width="formLabelWidth">
          <el-input
            v-model="emergency.emergencyInfo"
            autocomplete="off"
            maxlength="500"
            show-word-limit
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 20 }"
            placeholder="请输入内容"
          />
        </el-form-item>

        <el-form-item prop="emergencyTime" label="事件时间">
          <el-date-picker
            v-model="emergency.emergencyTime"
            type="datetime"
            placeholder="选择时间"
            format="yyyy -MM - dd  hh：mm：ss"
            value-format="yyyy-MM-dd hh:mm:ss"
            style="width:245px"
          />
        </el-form-item>

        <el-form-item prop="emergencyType" label="事件类型" :label-width="formLabelWidth">
          <el-select v-model="emergency.emergencyType" placeholder="请选择">
            <el-option
              v-for="item in emergencyType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="emergencyStudentId" label="相关学生">
          <el-select v-model="emergency.emergencyStudentId" placeholder="请选择" style=" width:100%">
            <el-option
              v-for="item in child"
              :key="item.studentId"
              :label="item.String"
              :value="item.studentId"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="emergencyClazzId" label="相关班级">
          <el-select v-model="emergency.emergencyClazzId" placeholder="请选择" style=" width:100%">
            <el-option
              v-for="item in classList"
              :key="item.classId"
              :label="item.className"
              :value="item.classId"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="emergencyClazzSkcd" label="上课次数" :label-width="formLabelWidth">
          <el-input v-model="emergency.emergencyClazzSkcd" autocomplete="off" maxlength="32" />
        </el-form-item>

        <el-form-item prop="emergencyStaffId" label="相关负责人">
          <el-select v-model="emergency.emergencyStaffId" placeholder="请选择" style=" width:100%">
            <el-option
              v-for="item in staff"
              :key="item.staffId"
              :label="item.String"
              :value="item.staffId"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="emergencyStatus" label="突发事件状态">
          <el-select v-model="emergency.emergencyStatus" placeholder="请选择">
            <el-option
              v-for="item in emergencyStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>

        </el-form-item>

        <el-form-item prop="emergencySolution" label="解决方案" :label-width="formLabelWidth">
          <el-input
            v-model="emergency.emergencySolution"
            autocomplete="off"
            maxlength="500"
            show-word-limit
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 20 }"
            placeholder="请输入内容"
          />
        </el-form-item>

        <el-form-item prop="emergencyExecute" label="执行记录" :label-width="formLabelWidth">
          <el-input
            v-model="emergency.emergencyExecute"
            autocomplete="off"
            maxlength="500"
            show-word-limit
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 20 }"
            placeholder="请输入内容"
          />
        </el-form-item>

        <el-form-item prop="emergencyConclusion" label="事件总结" :label-width="formLabelWidth">
          <el-input
            v-model="emergency.emergencyConclusion"
            autocomplete="off"
            maxlength="500"
            show-word-limit
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 20 }"
            placeholder="请输入内容"
          />
        </el-form-item>

        <!-- <el-form-item prop="emergencyMold" label="事件团体" :label-width="formLabelWidth">
          <el-radio v-model="emergency.emergencyMold" label="0">个人事件</el-radio>
          <el-radio v-model="emergency.emergencyMold" label="1">团体事件</el-radio> -->
        <!-- <el-input v-model="emergency.emergencyMold" autocomplete="off" maxlength="120" show-word-limit /> -->
        <!-- </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose">取 消</el-button>
        <el-button v-if="editType == 2" type="primary" @click="handleUpdate('emergency')">修 改</el-button>
        <el-button v-if="editType == 1" type="primary" @click="handleAddUser('emergency')">添 加</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAllemergency, addemergency, deleteemergency, updateemergency, getemergencyById } from '@/api/emergency'
import { selectStudent } from '@/api/child'
import { getAllClass } from '@/api/class'
import { selectstaff } from '@/api/staff'
import { validateChineseName, validatePhoneTwo, validateEMail, checkSpecificKey, validateCharacter, btKeyUp, isInteger } from '@/api/validata'

export default {
  data() {
    return {
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      // list: [],
      tableList: [],
      studentId: '',
      stulist: '',
      stafflist: '',
      child: {},
      staff: {},
      classList: {},
      listLoading: false,
      dialogFormVisible: false,
      editType: 1, // 1 添加 2 修改
      searchTableInfo: '',
      emergency: {
        emergencyMold: 0
      },
      newEmergency: {
        emergencyId: '',
        emergencyTitle: '',
        emergencyLoc: '',
        emergencyStatus: '',
        emergencyType: ''
      },
      formLabelWidth: '200px',
      rules: {
        emergencyTitle: [
          { required: true, message: '突发事件标题不能为空', trigger: 'blur' }
          // { validator: validateChineseName, message: '请输入中文', trigger: ['blur', 'change'] }
        ],
        emergencyTitle: [
          { required: true, message: '突发事件标题不能为空', trigger: 'blur' }
          // { validator: validateChineseName, message: '请输入中文', trigger: ['blur', 'change'] }
        ],
        emergencyInfo: [
          { required: true, message: '突发事件信息不能为空', trigger: 'blur' }
          // { validator: validateChineseName, message: '请输入中文', trigger: ['blur', 'change'] }
        ],
        emergencySolution: [
          { required: true, message: '解决方案不能为空', trigger: 'blur' }
          // { validator: validateChineseName, message: '请输入中文', trigger: ['blur', 'change'] }
        ],
        emergencyStaffId: [
          { required: true, message: '相关责任人不能为空', trigger: 'blur' }
        ],
        emergencyExecute: [
          { required: true, message: '执行记录不能为空', trigger: 'blur' }
          // { validator: validateChineseName, message: '请输入中文', trigger: ['blur', 'change'] }
        ],
        emergencyConclusion: [
          { required: true, message: '事件总结不能为空', trigger: 'blur' }
          // { validator: validateChineseName, message: '请输入中文', trigger: ['blur', 'change'] }
        ],
        emergencyClazzSkcd: [
          { required: true, message: '上课次数不能为空', trigger: 'blur' },
          { validator: isInteger, trigger: ['blur', 'change'] }],
        emergencyStatus: [
          { required: true, message: '突发事件状态不能为空', trigger: 'blur' }
        ],
        emergencyTime: [
          { required: true, message: '突发事件时间不能为空', trigger: 'blur' }
        ],
        emergencyType: [
          { required: true, message: '突发事件类型不能为空', trigger: 'blur' }
        ],
        emergencyClazzId: [
          { required: true, message: '相关班级不能为空', trigger: 'blur' }
        ],
        emergencyStudentId: [
          { required: true, message: '相关学生不能为空', trigger: 'blur' }
        ],
        emergencyMold: [
          { required: true, message: '事件团体不能为空', trigger: 'blur' }
        ]
      },
      emergencyType: [
        {
          value: 0,
          label: '设施问题'
        },
        {
          value: 1,
          label: '人员问题'
        },
        {
          value: 2,
          label: '学员问题'
        },
        {
          value: 3,
          label: '财务问题'
        },
        {
          value: 4,
          label: '家长问题'
        },
        {
          value: 5,
          label: '其他'
        }
      ],
      emergencyStatus: [
        {
          value: 0,
          label: '处理中'
        },
        {
          value: 1,
          label: '已解决'
        }
      ],
      emergencyTime: ''

    }
  },
  computed: {
    // 根据计算属性模糊搜索
    list() {
      const searchTableInfo = this.searchTableInfo
      console.log(this.searchTableInfo)
      if (searchTableInfo) {
        // filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
        // 注意： filter() 不会对空数组进行检测。
        // 注意： filter() 不会改变原始数组。
        return this.tableList.filter(data => {
          console.log('success' + data)
          // some() 方法用于检测数组中的元素是否满足指定条件;
          // some() 方法会依次执行数组的每个元素：
          // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
          // 如果没有满足条件的元素，则返回false。
          // 注意： some() 不会对空数组进行检测。
          // 注意： some() 不会改变原始数组。
          return Object.keys(data).some(key => {
            // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
            // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
            return String(data[key]).toLowerCase().indexOf(searchTableInfo) > -1
          })
        })
      }
      return this.tableList
    }
  },
  created() {
    this.getinfo()
    this.fetchData()
  },
  methods: {
    getinfo: function() {
      selectStudent().then((resp) => {
        this.child = resp.obj
        console.log(this.child)
      })
      selectstaff().then((resp) => {
        this.staff = resp.obj
        console.log(this.staff)
      })
      getAllClass().then((resp) => {
        this.classList = resp.obj
        console.log(this.classList)
      })
    },
    // 每页下拉显示数据
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    handleClick(row) {
      console.log(row)
    },
    // 接收table数据
    fetchData() {
      this.tableList = []
      this.listLoading = true
      getAllemergency().then((data) => {
        // this.tableList = data.obj
        this.newEmergency
        for (var i = 0; i < data.obj.length; i++) {
          this.newEmergency.emergencyId = data.obj[i].emergencyId
          this.newEmergency.emergencyTitle = data.obj[i].emergencyTitle
          // this.newEmergency. = data.obj[i].
          this.newEmergency.emergencyInfo = data.obj[i].emergencyInfo
          this.newEmergency.emergencyTime = data.obj[i].emergencyTime
          if (data.obj[i].emergencyStatus === 0) {
            this.newEmergency.emergencyStatus = '处理中'
          }
          if (data.obj[i].emergencyStatus === 1) {
            this.newEmergency.emergencyStatus = '已解决'
          }
          if (data.obj[i].emergencyType === 0) {
            this.newEmergency.emergencyType = '设施问题'
          }
          if (data.obj[i].emergencyType === 1) {
            this.newEmergency.emergencyType = '人员问题'
          }
          if (data.obj[i].emergencyType === 2) {
            this.newEmergency.emergencyType = '学员问题'
          }
          if (data.obj[i].emergencyType === 3) {
            this.newEmergency.emergencyType = '财务问题'
          }
          if (data.obj[i].emergencyType === 4) {
            this.newEmergency.emergencyType = '家长问题'
          }
          if (data.obj[i].emergencyType === 5) {
            this.newEmergency.emergencyType = '其他'
          }
          this.tableList.push(this.newEmergency)
          this.newEmergency = {}
        }
        console.log(this.tableList)
        this.listLoading = false
      })
    },
    handleDelete(id, username) {
      this.$confirm('确认删除该事件？').then(() =>
        deleteemergency(id).then((data) => {
          this.$notify({
            title: '操作成功',
            type: 'success'
          })
          const totalPage = Math.ceil((this.list.length - 1) / this.pagesize)
          const page =
            this.currentPage > totalPage ? totalPage : this.currentPage
          this.currentPage = this.currentPage < 1 ? 1 : page
          this.fetchData()
        })
      )
    },
    handleAddUser(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // var studentId = ''
          // console.log('传过来的值', this.emergency)
          // for (var i = 0; i < this.emergency.emergencyStudentId.length; i++) {
          //   studentId += (this.emergency.emergencyStudentId[i])
          // }
          // this.emergency.emergencyStudentId = studentId

          // var staffId = ''
          // for (var i = 0; i < this.emergency.emergencyStaffId.length; i++) {
          //   staffId += (this.emergency.emergencyStaffId[i])
          // }
          // this.emergency.emergencyStaffId = staffId

          // var classId = ''
          // for (var i = 0; i < this.emergency.emergencyClazzId.length; i++) {
          //   classId += (this.emergency.emergencyClazzId[i])
          // }
          // this.emergency.emergencyClazzId = classId

          // this.emergency.mergencyTimeToString = this.emergency.emergencyTime
          console.log('添加的信息', this.emergency)
          addemergency(this.emergency).then((resp) => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.emergency = {}
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleOpen(title, type, id) {
      this.emergency = {}
      this.title = title
      this.editType = type
      if (type === 2) {
        getemergencyById(id).then((resp) => {
          this.emergency = resp.obj
          console.log('通过id查询信息', this.emergency)
          this.emergency.emergencyMold = String(this.emergency.emergencyMold)
        })
        this.dialogFormVisible = true
      } else {
        this.dialogFormVisible = true
      }
    },
    handleClose() {
      this.dialogFormVisible = false
      this.emergency = {}
    },
    handleUpdate(formName) {
      this.emergency.emergencyTimeToString = this.emergency.emergencyTime
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.studentId = ''
          // for (var i = 0; i < this.emergency.emergencyChild.length; i++) {
          //   this.studentId += (this.emergency.emergencyChild[i] + ';')
          // }
          this.emergency.emergencyChild = this.studentId

          this.staffId = ''
          // for (var i = 0; i < this.emergency.staffId.length; i++) {
          //   this.staffId += (this.emergency.staffId[i] + ';')
          // }
          this.emergency.staffId = this.staffId
          console.log(this.emergency)
          updateemergency(this.emergency).then((resp) => {
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    emType: (row, column) => {
      if (row.emergencyType === 0) {
        return '设施问题'
      }
      if (row.emergencyType === 1) {
        return '人员问题'
      }
      if (row.emergencyType === 2) {
        return '学员问题'
      }
      if (row.emergencyType === 3) {
        return '财务问题'
      }
      if (row.emergencyType === 4) {
        return '家长问题'
      }
      if (row.emergencyType === 5) {
        return '其他'
      }
    },
    emStatus: (row, column) => {
      if (row.emergencyStatus === 0) {
        return '处理中'
      }
      if (row.emergencyStatus === 1) {
        return '已解决'
      }
    }
  }
}
</script>

<style scoped>
#main {
  margin-left: 5px;
  margin-right: 5px;
}
#table-area {
  margin-left: 10px;
  margin-right: 10px;
}
</style>
